<script lang="ts" setup>
import { useTemplateRef, watch, computed, onMounted } from 'vue';
import { onClickOutside } from '@vueuse/core';

const props = defineProps({
  placeholder: {
    type: String,
    default: '',
  },

  disabled: {
    type: Boolean,
    default: false,
  },
});

const contentValue = defineModel<string>();
const emit = defineEmits(['submit', 'blur']);
const textareaRef = useTemplateRef('textareaEl');
const rootRef = useTemplateRef('rootEl');

onClickOutside(rootRef, () => emit('blur'));

const MAX_LENGTH = 1000;

// TODO: 内容长度计算可以更复杂，比如剔除标点符号等特殊字符
const contentLength = computed(() => contentValue.value?.length ?? 0);

const overMaxLength = computed(() => contentLength.value > MAX_LENGTH);

const sendDisabled = computed(() => props.disabled || overMaxLength.value || contentLength.value === 0);

watch(contentValue, () => {
  if (textareaRef.value) {
    textareaRef.value.style.height = 'auto';
    textareaRef.value.style.height = `${textareaRef.value.scrollHeight}px`;
  }
});

const handleClick = () => {
  emit('submit', contentValue.value);
}

onMounted(() => {
  textareaRef.value?.focus();
});
</script>

<template>
  <div class="component-comment-input text-#292929" ref="rootEl">
    <textarea
      class="min-h-96 w-full resize-none border-none text-16 leading-24 focus-visible:outline-unset"
      :placeholder="props.placeholder"
      v-model="contentValue"
      ref="textareaEl"
    >
    </textarea>
    <div class="mt-20 flex-y-center justify-end gap-x-20">
      <div class="flex-y-center gap-x-0.4em text-14">
        <span :class="overMaxLength ? 'text-#E24E40' : ''">{{ contentLength }}</span>
        <span :class="overMaxLength ? 'text-#E24E40' : 'text-#8b8b8b'">/</span>
        <span :class="overMaxLength ? 'text-#E24E40' : 'text-#8b8b8b'">{{ MAX_LENGTH }}</span>
      </div>
      <button
        type="button"
        class="h-32 rounded-4 px-23 text-14"
        :class="sendDisabled ? 'bg-#f7f7f7 text-#8b8b8b cursor-not-allowed' : 'bg-#3D7CFA text-white'"
        :disabled="sendDisabled"
        @click="handleClick"
      >
        {{ $t('home.explore.comments.send') }}
      </button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
</style>
